package com.west.xu.jdbc.base;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.west.xu.jdbc.utils.StringUtilTemporary;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Type;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;


public class BulkInsertService {
    private static final Logger log = LoggerFactory.getLogger(BulkInsertService.class);

    public static int bulkInsert(DruidDataSource dataSource,
                                 String tableName,
                                 Type clazz,
                                 List<String> jsonList,
                                 List<String> insertColumns) {
        StringBuilder sqlBuf = new StringBuilder();
        sqlBuf.append("INSERT INTO ").append(tableName).append(" (").append(String.join(",", insertColumns)).append(") VALUES ");
        String values = StringUtilTemporary.getFieldListToString(jsonList, insertColumns, clazz);
        sqlBuf.append(values);

        PreparedStatement statement = null;
        DruidPooledConnection conn = null;
        int result = 0;
        try {
            conn = dataSource.getConnection();
            conn.setAutoCommit(false);
            statement = conn.prepareStatement(sqlBuf.toString());
            result = statement.executeUpdate();
            conn.commit();
            long finish = System.currentTimeMillis();
//            log.info("Execute Insert Success|totalSize=" + jsonList.size() + " Cost=" + (finish - start) + "ms");
        } catch (Exception sqle) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
                log.error("rollback error|" + e1.getMessage());
            }
            log.error("execute error|" + sqle.getMessage());
            throw new RuntimeException("executeInsert error|" + sqle.getMessage());
        } finally {
            try {
                if (statement != null) {
                    statement.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException sqle) {
                log.error("close Connection error|" + sqle.getMessage());
            }
        }
        return result;
    }
}
